#import <UIKit/UIKit.h>
#import "DumbDownloadManager.h"

#define DELEGATE_CALLBACK(X, Y) if (self.delegate && [self.delegate respondsToSelector:@selector(X)]) [self.delegate performSelector:@selector(X) withObject:Y];
#define kIMGCancel @"cancel.png"

@implementation DumbDownloadManager

- (void)start
{
    //NSLog(@"start");
	if (_fileURL == nil) {
		return;
	}
    //NSLog(@"start2");
	NSURLRequest *request = [NSURLRequest requestWithURL:_fileURL];
	self.URLConnection = [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    //NSLog(@"didReceiveResponse");
//	self.currentSize = 0;
//    self.totalFileSize = [NSNumber numberWithLongLong:[response expectedContentLength]];
	//NSLog(@"totalFileSize:%lld", [response expectedContentLength]);
	// Check for bad connection
	if ([response expectedContentLength] < 0) {
		NSString *reason = [NSString stringWithFormat:@"Invalid URL [%@]", [_fileURL absoluteString]];
		//DELEGATE_CALLBACK(downloadManagerDataDownloadFailed:, reason);
		DELEGATE_CALLBACK(dumbDownloadManagerDataDownloadFailed:, reason);
        
		[connection cancel];
		return;
	}
	
	if ([response suggestedFilename])
		DELEGATE_CALLBACK(downloadManagerDidReceiveData:, [response suggestedFilename]);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    //NSLog(@"didReceiveData");
	[self writeToFile:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    //NSLog(@"didFailWithError");
	//[_progressAlertView dismissWithClickedButtonIndex:0 animated:YES];
}

-(void)writeToFile:(NSData *)data{
    //NSLog(@"writeToFile");
	NSString *filePath=[NSString stringWithFormat:@"%@",_fileName];
	if([[NSFileManager defaultManager] fileExistsAtPath:filePath] == NO){
		[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
	}
	FILE *file = fopen([_fileName UTF8String], [@"ab+" UTF8String]);
	if(file != NULL){
		fseek(file, 0, SEEK_END);
	}
	int readSize = [data length];
	fwrite((const void *)[data bytes], readSize, 1, file);
	fclose(file);
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    //NSLog(@"connectionDidFinishLoading");
	DELEGATE_CALLBACK(dumbDownloadManagerDataDownloadFinished:, _fileName);	
}

@synthesize delegate = _delegate;
@synthesize title = _title;
@synthesize fileURL = _fileURL;
@synthesize fileName = _fileName;
@synthesize URLConnection = _URLConnection;

- (void)dealloc{
    _delegate = nil;
    [_title release];
    [_fileURL release];
    [_fileName release];
    [_URLConnection release];
    [super dealloc];
}

@end








